package com.example.flashsales.service.impl;


import com.example.flashsales.entity.dto.GoodsDto;
import com.example.flashsales.entity.dto.OrderDetailsDto;
import com.example.flashsales.entity.dto.OrderDto;
import com.example.flashsales.entity.pojo.Order;
import com.example.flashsales.entity.pojo.OrderDetails;
import com.example.flashsales.entity.pojo.TimeConfig;
import com.example.flashsales.entity.vo.GoodsVo;
import com.example.flashsales.entity.vo.OrderDetailsVo;
import com.example.flashsales.entity.vo.OrdersVo;
import com.example.flashsales.entity.vo.StoreVo;
import com.example.flashsales.mappers.OrderMapper;
import com.example.flashsales.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;

    @Autowired
    GoodsServiceImpl goodsService;

    @Autowired
    StoreServiceImpl storeService;

    @Autowired
    TimeServiceImpl timeService;

    /**
     *  添加一个订单
     * @param orderDto 订单信息
     * @return 返回是否添加成功
     */
    @Override
    @Transactional
    public boolean addOrder(OrderDto orderDto) {
        if (orderDto == null){
            return false;
        }
        //添加了一个订单
        if (orderMapper.addOrder(orderDto) > 0) {
            //订单细节
            for (Long goodsId : orderDto.getMap().keySet()) {
                double mon = (goodsService.viewGoodsMessage(goodsId).getPrice()) * (orderDto.getMap().get(goodsId));
                OrderDetailsDto orderDetailsDto = new OrderDetailsDto();
                orderDetailsDto.setOrderId(orderDto.getId());
                orderDetailsDto.setCount(orderDto.getMap().get(goodsId));
                orderDetailsDto.setGoodsId(goodsId);
                orderDetailsDto.setMoney(mon);
                if (orderMapper.addDetails(orderDetailsDto) <= 0) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 用户查看自己的订单
     * @param userId 用户id
     * @return 返回用户的订单视图对象列表
     */
    public List<OrdersVo> viewOrders(long userId,int page,int num){
        if (page <= 0){
            return null;
        }
        page = (page-1)*num;
        final List<Order> orders = orderMapper.viewOrders(userId,page,num);
        return tools(orders);
    }


    /**
     *  用户按时间查看自己的订单
     * @param userId 用户id
     * @param qDate 前一天
     * @param hDate 后一天
     * @return 返回用户的订单视图对象列表
     */
    public List<OrdersVo> viewOrdersByTime(long userId,Date qDate,Date hDate,int page,int num){
        if (page <= 0){
            return null;
        }
        page = (page - 1 )*num;
        final List<Order> orderDetails = orderMapper.viewOrdersByTime(qDate, hDate, userId, page, num);
        return tools(orderDetails);
    }




    /**
     * 修改订单状态
     * @param orderId 订单id
     * @param state 状态 状态 0送达小店 1未送达小店  2已收货 3已分拣 4已下单未支付 5确任收货 6已付款未分拣
     * @return
     */
    @Override
    public boolean updateOrderState(long orderId, int state) {
        return orderMapper.updateOrderState(orderId, state) > 0;
    }


    /**
     * TODO 确认订单到达小店
     * @param orderId 订单id
     * @return
     */
    @Override
    public boolean updateOrderByArrive(long orderId) {
        Date date = new Date();
        if (orderMapper.updateOrderByArrive(orderId,date) > 0) {
            return true;
        }
        return false;
    }

    /**
     * 店家查看自己的订单
     * @param storeId 店家id
     * @param page 页数
     * @param num 条数
     * @return 返回订单视图对象
     */
    @Override
    public List<OrdersVo> viewStoreOrder(long storeId, int page, int num) {
        if (page < 1){
            return null;
        }
        page = (page - 1)*num;
        final List<Order> orders = orderMapper.viewStoreOrder(storeId, page, num);
        return tools(orders);
    }


    /**
     * 店家按时间查看订单
     * @param storeId 店家id
     * @param page 页数
     * @param num 条数
     * @param qDate 前一天
     * @param hDate 后一天
     * @return 返回订单视图对象
     */
    @Override
    public List<OrdersVo> viewStoreOrderByTime(long storeId, int page, int num, Date qDate, Date hDate) {
        if (page < 1){
            return null;
        }
        page = (page - 1)*num;
        final List<Order> orders = orderMapper.viewStoreOrderByTime(storeId, page, num, qDate, hDate);
        return tools(orders);
    }

    /**
     * 根据订单id获取订单
     * @param orderId 订单id
     * @return
     */
    @Override
    public List<OrdersVo> viewOrder(long orderId) {
        final Order order = orderMapper.viewOrder(orderId);
        if (order == null){
            return null;
        }
        List<Order> list = new ArrayList<>();
        list.add(order);
        return tools(list);
    }

    /**
     * 根据用户id获取订单的id集合
     * @param userId
     * @return
     */
    @Override
    public List<Integer> viewOrderIdByUser(long userId) {
        return orderMapper.viewOrderIdByUser(userId);
    }


    /**
     * 修改订单信息
     * @param orderId 订单id
     * @param map key为商品id，value为退货的数量
     * @return 返回是否修改成功
     */
    @Override
    @Transactional
    public boolean updateOrder(long orderId, Map<Long,Double> map) {
        final List<OrdersVo> ordersVoList = viewOrder(orderId);
        if (ordersVoList.isEmpty()){
            return false;
        }
        final OrdersVo ordersVo = ordersVoList.get(0);
        final List<OrderDetailsVo> orderDetailsVoList = ordersVo.getOrderDetailsVoList();
        boolean flag = true;
        //退款金额
        double returnMoney = 0.0;
        for (Long aLong : map.keySet()) {
            GoodsVo goodsVo = goodsService.viewGoodsMessage(aLong);
            returnMoney = returnMoney + goodsVo.getPrice()*map.get(aLong);
            for (OrderDetailsVo orderDetailsVo : orderDetailsVoList) {
                if (orderDetailsVo.getGoodsId() == aLong){
                    //商品的实际购买数量
                    double sCount = orderDetailsVo.getXCount() - map.get(aLong);
                    //实际支付的金额
                    double m = orderDetailsVo.getMoney() - goodsVo.getPrice()*map.get(aLong);
                    if (orderMapper.updateOrderDetails(orderId,goodsVo.getId(),sCount,m) <= 0) {
                        flag = false;
                    }
                }
            }
        }
        if (flag){
            //实际支付金额
            double payMoney = ordersVo.getPayMoney() - returnMoney;
            if (orderMapper.updateOrder(orderId,returnMoney,payMoney) > 0) {
                //修改订单状态成功
                return true;
            }
        }
        return false;
    }


    /**
     * 查询会员订单总量
     * @param userId
     * @return
     */
    @Override
    public Integer viewUserOrderCount(long userId) {
        return orderMapper.viewUserOrderCount(userId);
    }


    /**
     * 查看当天的订单
     * @return
     */
    @Override
    public List<OrdersVo> viewAllOrderByDay(Integer num,Integer page) {
        final TimeConfig timeConfig = timeService.viewTime();
        //每天截止时间
        final Time time = timeConfig.getTime();
        Date date = new Date();
        Date date1 = new Date();
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date);
        calendar1.add(Calendar.DATE, -1);
        date1 = calendar1.getTime();
        //当天
        final String format = new SimpleDateFormat("yyyy-MM-dd").format(date1);
        final String d = format +" "+ time;
        //前一天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -2);
        date = calendar.getTime();
        final String format1 = new SimpleDateFormat("yyyy-MM-dd").format(date);
        final String q = format1 +" "+ time;

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date qDate = null;
        Date hDate = null;
        try {
            qDate = f.parse(q);
            hDate = f.parse(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        final List<Order> list = orderMapper.viewAllOrderByTime(hDate, qDate,(page - 1)*num,num);
        return tools(list);
    }


    /**
     * 查看当天各种商品的总量
     * @return
     */
    @Override
    public List<GoodsVo> viewGoodsWeight() {
        List<GoodsVo> list = new ArrayList<>();
        final TimeConfig timeConfig = timeService.viewTime();
        //每天截止时间
        final Time time = timeConfig.getTime();
        Date date = new Date();
        Date date1 = new Date();
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date1);
        calendar1.add(Calendar.DATE, -1);
        date1 = calendar1.getTime();
        //当天
        final String format = new SimpleDateFormat("yyyy-MM-dd").format(date1);
        final String d = format +" "+ time;
        //前一天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -2);
        date = calendar.getTime();
        final String format1 = new SimpleDateFormat("yyyy-MM-dd").format(date);
        final String q = format1 +" "+ time;

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date qDate = null;
        Date hDate = null;
        try {
            qDate = f.parse(q);
            hDate = f.parse(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        final List<Order> ordersVoList = orderMapper.viewAllOrderByDayWeight(qDate,hDate);
        for (OrdersVo ordersVo : tools(ordersVoList)) {
            final List<OrderDetailsVo> orderDetailsVoList = ordersVo.getOrderDetailsVoList();
            for (OrderDetailsVo orderDetailsVo : orderDetailsVoList) {
                GoodsVo goodsVo = new GoodsVo();
                final GoodsVo goodsVo1 = goodsService.viewGoodsMessage(orderDetailsVo.getGoodsId());
                goodsVo.setType(goodsVo1.getType());
                goodsVo.setName(goodsVo1.getName());
                goodsVo.setCount(orderDetailsVo.getXCount());
                goodsVo.setId(goodsVo1.getId());
                if (!list.contains(goodsVo)){
                    list.add(goodsVo);
                }else {
                    for (GoodsVo vo : list) {
                        if (vo.getId() == goodsVo.getId()){
                            vo.setCount(vo.getCount()+goodsVo.getCount());
                        }
                    }
                }
            }
        }
        return list;
    }

    /**
     * 修改订单的支付金额与支付方式
     * @param orderId
     * @param method
     * @param money
     * @return
     */
    @Override
    public boolean updateMoneyAndMethod(long orderId, int method, double money) {
        final List<OrdersVo> ordersVoList = viewOrder(orderId);
        if (ordersVoList.isEmpty()){
            return false;
        }
        final OrdersVo ordersVo = ordersVoList.get(0);
        if (ordersVo.getOrderMoney() != money){
            return false;
        }
        return orderMapper.updateMoneyAndMethod(orderId, method, money) > 0;
    }


    /**
     * 查看店家订单的总数
     * @param storeId
     * @return
     */
    @Override
    public long viewStoreOrderCount(long storeId) {
        return orderMapper.viewStoreOrderCount(storeId);
    }

    /**
     * 用户按时间查看订单的总数
     * @param userId
     * @param qDate
     * @param hDate
     * @return
     */
    @Override
    public Integer viewUserOrderCountByTime(long userId, Date qDate, Date hDate) {
        return orderMapper.viewUserOrderCountByTime(userId,qDate,hDate);
    }


    /**
     * 商家按时间查看订单总数
     * @param id
     * @param qDate
     * @param hDate
     * @return
     */
    @Override
    public long viewStoreOrderCountByTime(long id, Date qDate, Date hDate) {
        return orderMapper.viewStoreOrderCountByTime(id,qDate,hDate);
    }

    /**
     * 删除超时订单
     * @return
     */
    @Override
    public List<Long> delete() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, -30);
        date = calendar.getTime();
        final List<Long> list = orderMapper.viewOrderInTimer(date);
        if (list == null || list.isEmpty()){
            return null;
        }
        for (Long aLong : list) {
            final List<OrderDetailsVo> orderDetailsVoList = viewOrder(aLong).get(0).getOrderDetailsVoList();
            for (OrderDetailsVo orderDetailsVo : orderDetailsVoList) {
                GoodsDto goodsDto = new GoodsDto();
                goodsDto.setId(orderDetailsVo.getGoodsId());
                final double count = goodsService.viewGoodsMessage(orderDetailsVo.getGoodsId()).getCount();
                goodsDto.setCount(orderDetailsVo.getXCount()+count);
                if (!goodsService.updateGoodsMessage(goodsDto)) {
                    return null;
                }
            }
            if (!(orderMapper.deleteOrder(aLong) > 0)) {
                return null;
            }
        }
        return list;
    }

    /**
     * 取消订单
     * @param orderId
     * @return
     */
    @Override
    @Transactional
    public boolean cancelOrder(long orderId) {
        final List<OrdersVo> ordersVoList = viewOrder(orderId);
        if (ordersVoList == null){
            return false;
        }
        final OrdersVo ordersVo = ordersVoList.get(0);
        if (ordersVo.getState() != 4){
            return false;
        }
        for (OrderDetailsVo orderDetailsVo : ordersVo.getOrderDetailsVoList()) {
            GoodsDto goodsDto = new GoodsDto();
            final GoodsVo goodsVo = goodsService.viewGoodsMessage(orderDetailsVo.getGoodsId());
            goodsDto.setCount(orderDetailsVo.getXCount()+goodsVo.getCount());
            goodsDto.setId(orderDetailsVo.getGoodsId());
            if (!goodsService.updateGoodsMessage(goodsDto)) {
                return false;
            }
        }
        return orderMapper.deleteOrder(orderId) > 0;
    }

    /**
     * 查看所有订单
     * @param page
     * @param num
     * @return
     */
    @Override
    public Map<String, Object> viewAllOrder(int page, int num) {
        final List<Order> list = orderMapper.viewAllOrder((page - 1) * num, num);
        final List<OrdersVo> tools = tools(list);
        final Integer integer = orderMapper.viewAllOrderCount();
        Map<String,Object> map = new HashMap<>();
        map.put("total",integer);
        map.put("message",tools);
        return map;
    }

    /**
     * 根据时间类型查看
     * @param page
     * @param num
     * @param qDate
     * @param hDate
     * @param state
     * @return
     */
    @Override
    public Map<String, Object> viewAllOrderByStateAndTime(int page, int num, Date qDate, Date hDate, int state) {
        final List<Order> list = orderMapper.viewAllOrderByStateAndTime((page - 1) * num, num, qDate, hDate, state);
        final List<OrdersVo> tools = tools(list);
        final Integer integer = orderMapper.viewCountByStateAndTime(qDate, hDate, state);
        Map<String,Object> map = new HashMap<>();
        map.put("total",integer);
        map.put("message",tools);
        return map;
    }

    /**
     * 查看当天订单总数
     * @return
     */
    @Override
    public Integer vieOrderDayCount() {

        final TimeConfig timeConfig = timeService.viewTime();
        //每天截止时间
        final Time time = timeConfig.getTime();
        Date date = new Date();
        Date date1 = new Date();
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date);
        calendar1.add(Calendar.DATE, -1);
        date1 = calendar1.getTime();
        //当天
        final String format = new SimpleDateFormat("yyyy-MM-dd").format(date1);
        final String d = format +" "+ time;
        //前一天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -2);
        date = calendar.getTime();
        final String format1 = new SimpleDateFormat("yyyy-MM-dd").format(date);
        final String q = format1 +" "+ time;

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date qDate = null;
        Date hDate = null;
        try {
            qDate = f.parse(q);
            hDate = f.parse(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        final Integer integer = orderMapper.viewAllTimeCount(qDate, hDate);
        return integer;
    }


    /**
     * 查看当天未分拣
     * @param page
     * @param num
     * @return
     */
    @Override
    public List<OrderDetails> viewAllDetails(Integer page, Integer num) {
        final TimeConfig timeConfig = timeService.viewTime();
        //TODO 只能查看到前天晚上六点到昨天晚上六点
        final Time time = timeConfig.getTime();
        Date date = new Date();
        Date date1 = new Date();
        //当天
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date1);
        calendar1.add(Calendar.DATE, -1);
        date1 = calendar1.getTime();
        final String format = new SimpleDateFormat("yyyy-MM-dd").format(date1);
        final String d = format +" "+ time;
        //前一天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -2);
        date = calendar.getTime();
        final String format1 = new SimpleDateFormat("yyyy-MM-dd").format(date);
        final String q = format1 +" "+ time;

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date qDate = null;
        Date hDate = null;
        try {
            qDate = f.parse(q);
            hDate = f.parse(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return orderMapper.viewAllDetails(qDate,hDate,(page - 1)*num,num);
    }

    /**
     * 封装工具
     * @param orders
     * @return
     */
    private List<OrdersVo> tools(List<Order> orders){
        List<OrdersVo> ordersVoList = new ArrayList<>();
        //拿到所有订单
        for (Order order : orders) {
            //封装订单视图
            OrdersVo ordersVo = new OrdersVo();
            BeanUtils.copyProperties(order,ordersVo);
            //拿到订单的细节
            List<OrderDetails> orderDetails = orderMapper.viewOrderDetails(order.getId());
            List<OrderDetailsVo> orderDetailsVoList = new ArrayList<>();
            for (OrderDetails orderDetail : orderDetails) {
                //封装视图
                OrderDetailsVo orderDetailsVo = new OrderDetailsVo();
                BeanUtils.copyProperties(orderDetail,orderDetailsVo);
                //获取商品信息
                GoodsVo goodsVo = goodsService.viewGoodsMessage(orderDetailsVo.getGoodsId());
                orderDetailsVo.setGoodsMoney(goodsVo.getPrice());
                orderDetailsVo.setName(goodsVo.getName());
                orderDetailsVoList.add(orderDetailsVo);
            }
            ordersVo.setOrderDetailsVoList(orderDetailsVoList);
            if (ordersVo.getMethod() == 0){
                //余额
                ordersVo.setPay("余额");
            }else if (ordersVo.getMethod() == 1){
                //支付宝
                ordersVo.setPay("支付宝");
            }else if (ordersVo.getMethod() == 2){
                //微信
                ordersVo.setPay("微信");
            }else if (ordersVo.getMethod() == 3){
                //支付宝加余额
                ordersVo.setPay("支付宝加余额");
            }else if (ordersVo.getMethod() == 4){
                //微信加余额
                ordersVo.setPay("微信加余额");
            }else {
                //未知
                ordersVo.setPay("未知");
            }
            //状态 0送达小店 1未送达小店  2已收货 3已分拣 4已下单未支付 5确任收货 6已付款未分拣
            if (ordersVo.getState() == 0){
                ordersVo.setNowState("送达小店");
            }else if (ordersVo.getState() == 1){
                ordersVo.setNowState("未送达小店");
            }else if (ordersVo.getState() == 2){
                ordersVo.setNowState("已收货");
            }else if (ordersVo.getState() == 3){
                ordersVo.setNowState("已分拣");
            }else if (ordersVo.getState() == 4){
                ordersVo.setNowState("已下单未支付");
            }else if (ordersVo.getState() == 5){
                ordersVo.setNowState("确认收货");
            }else if (ordersVo.getState() == 6){
                ordersVo.setNowState("已付款未分拣");
            }else {
                //未知
                ordersVo.setNowState("未知");
            }
            //获取店家名字
            final StoreVo storeVo = storeService.viewStoreMessage(ordersVo.getStoreId());
            ordersVo.setAddress(storeVo.getAddress());
            ordersVo.setStoreName(storeVo.getName());
            ordersVoList.add(ordersVo);
        }
        return ordersVoList;
    }


    /**
     * 按时间查看全部
     * @param page
     * @param num
     * @param qDate
     * @param hDate
     * @return
     */
    public Map<String, Object> viewAllByTime(int page, int num, Date qDate, Date hDate) {
        final List<Order> list = orderMapper.viewAllByTime((page - 1) * num, num, qDate, hDate);
        final List<OrdersVo> tools = tools(list);
        Map<String,Object> map = new HashMap<>();
        map.put("total",orderMapper.viewAllTimeCount(qDate,hDate));
        map.put("message",tools);
        return map;
    }
}
